<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <!-- <base-form
            :rule-form-config="ruleFormConfig"
            :rule-form-props="ruleFormProps"
            :rul-form-model="queryParams"
            @handle-query="handleQuery"
            @reset-query="resetQuery"
            @init-data="initData"
          >
          </base-form> -->
          <el-form inline :model="queryParams">
            <el-form-item label="机型" prop="aircraftModel">
              <el-select v-model="queryParams.aircraftModel">
                <el-option v-for="(item, index) in airModelList" :key="'model-item' + index" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="批次号" prop="track">
              <PageInput
                v-model:modelValue="queryParams.track"
                :aircraft-model="queryParams.aircraftModel"
                bom-detail-type="QBOM_SBOM_CHANGE"
                @init-data="initData"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
              <!-- <el-button icon="Refresh" @click="resetQuery">重置</el-button> -->
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="mb-[10px]">
        <el-card shadow="hover">
          <template #header>
            <div>
              <el-button v-hasPermi="['upload:model:status']" type="primary" plain @click="openCreateStatusList">有限元模型状态清单</el-button>
              <el-button v-hasPermi="['compare:model:status']" type="primary" plain @click="compareStrengthList">对比数模状态清单</el-button>
            </div>
          </template>
          <base-table
            v-loading="tableLoading"
            :table-headers="tableHeaders"
            :table-data="tableData"
            :table-props="tableProps"
            :table-events="tableEvents"
          >
            <template #handle="scope">
              <el-tooltip content="查看详情" placement="top">
                <el-button v-hasPermi="['strength:standard:detail']" link type="primary" icon="Promotion" @click="handleDetail(scope.data.row)" />
              </el-tooltip>
              <el-tooltip content="下载" placement="top">
                <el-button v-hasPermi="['strength:standard:download']" link type="primary" icon="Download" @click="handleDownload(scope.data.row)" />
              </el-tooltip>
            </template>
          </base-table>
          <pagination
            v-show="total > 0"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            :total="total"
            @pagination="initData"
          />
        </el-card>
      </div>
    </transition>
    <!-- 上传数模状态清单 -->
    <el-dialog v-if="statusDialog.visible" v-model="statusDialog.visible" :title="statusDialog.title" width="400px" append-to-body>
      <el-form ref="dialogFormRef" v-loading="diaLoading" :model="dialogForm" :rules="rules" label-width="80px">
        <el-form-item label="机型" prop="aircraftModel">
          <el-select v-model="dialogForm.aircraftModel" width="220px" clearabl>
            <el-option v-for="item in airModelList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="dialogForm.aircraftModel" label="批次号" prop="track">
          <PageInput v-model:modelValue="dialogForm.track" :aircraft-model="dialogForm.aircraftModel" bom-detail-type="QBOM" />
        </el-form-item>
        <el-form-item label="描述" prop="describe">
          <el-input v-model="dialogForm.describe" placeholder="请输入描述" type="textarea" :autosize="{ minRows: 2 }" />
        </el-form-item>
        <el-form-item label="上传文件" prop="file">
          <el-upload
            ref="uploadRef"
            class="upload-demo"
            action="#"
            :auto-upload="false"
            :before-upload="beforeUpload"
            :on-change="changeFile"
            :on-remove="handleRemove"
            :on-exceed="handleExceed"
            :limit="1"
          >
            <template #trigger>
              <el-button type="primary">选择文件</el-button>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="handleSure">确 定</el-button>
          <el-button @click="cancelCreate">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <select-list-dialog
      ref="selectListDialogRef"
      :aircraft-model="queryParams.aircraftModel"
      bom-detail-type="QBOM"
      @on-sure="handleDialogSure"
    ></select-list-dialog>
  </div>
</template>

<script setup name="strengthModelList" lang="ts">
import { genFileId } from 'element-plus';
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus';
import SelectListDialog from '@/views/bomCompareTool/strengthModelList/selectListDialog.vue';
import { uploadModelStatus } from '@/api/bomCompareTool/statusCompareStrength/index';
import PageInput from '@/components/PageInput/index.vue';
import { getStructureTree } from '@/api/elementsLibrary/index';
import { downloadData } from '@/api/bomCompareTool/strengthCompareStandard/index';
import { getStrengthList, generateList } from '@/api/bomCompareTool/strengthModelList/index';
const router = useRouter();
const queryParams = reactive({
  track: '',
  bomDetailType: 'QBOM_SBOM_CHANGE',
  aircraftModel: 'C919',
  pageNum: 1,
  pageSize: 10
});
const selectListDialogRef = ref<ElDialogInstance>();
const dialogFormRef = ref<ElFormInstance>();
const total = ref(1);
const statusDialog = reactive({
  visible: false,
  title: '上传数模状态清单'
});
const dialogVisible = ref(false);
const airModelList = ref([
  {
    label: 'C919',
    value: 'C919'
  },
  {
    label: 'C929',
    value: 'C929'
  }
]);
const ruleFormConfig = reactive([
  {
    prop: 'aircraftModel',
    type: 'BaseSelect',
    formItemProps: {
      label: '机型'
    },
    props: {
      disabled: false,
      clearable: false
    },
    options: airModelList.value
  },
  // {
  //   prop: 'track',
  //   type: 'BaseInput',
  //   formItemProps: {
  //     label: '批次号'
  //   },
  //   props: {
  //     disabled: false,
  //     clearable: false
  //   }
  // }
  {
    prop: 'track',
    type: 'PageSelect',
    formItemProps: {
      label: '批次号'
    },
    props: {
      disabled: false,
      clearable: false
    },
    bomDetailType: 'QBOM_SBOM_CHANGE',
    aircraftModel: queryParams.aircraftModel
  }
]);
const rulFormModel = reactive({
  aircraftModel: 'C919',
  track: ''
});
const ruleFormProps = reactive({
  inline: true,
  'label-width': '90'
});
const rules = reactive<ElFormRules>({
  aircraftModel: [{ required: true, message: '机型不能为空', trigger: 'change' }],
  file: [{ required: true, message: '文件不能为空', trigger: 'change' }],
  describe: [{ required: true, message: '描述不能为空', trigger: 'change' }]
});
const tableLoading = ref(false);
// 表格配置
const tableHeaders = [
  {
    columnProps: {
      type: 'selection',
      width: '35'
    }
  },
  {
    columnProps: { prop: 'name', label: '名称', minWidth: '180px' }
  },
  {
    columnProps: { prop: 'groupType', label: '组型', minWidth: '100px' }
  },
  {
    columnProps: { prop: 'modelStatusDesc', label: '描述', minWidth: '200px' }
  },
  {
    columnProps: { prop: 'createBy', label: '创建人', minWidth: '100px' }
  },
  {
    columnProps: { prop: 'createTime', label: '创建时间', minWidth: '180px' }
  },
  {
    columnProps: { prop: 'handle', label: '操作', width: '180px', fixed: 'right' },
    showColumnSlot: true,
    columnSlotName: 'handle'
  }
];
const tableProps = {
  style: {
    width: '100%'
  }
};
const multipleSelection = ref<Array<any>>([]);
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
};
const tableEvents = {
  'selection-change': handleSelectionChange
};

// 获取当前实例
const { proxy } = getCurrentInstance();

const showSearch = true;
// 装机清单列表
const initData = async () => {
  tableLoading.value = true;
  const res = await getStrengthList(queryParams);
  tableData.value = res.rows;
  total.value = res.total;
  tableLoading.value = false;
};
// 搜索
const handleQuery = () => {
  queryParams.pageNum = 1;
  initData();
};
// 重置
const resetQuery = () => {
  queryParams.aircraftModel = 'C919';
  handleQuery();
};
// 表格数据
const tableData = ref([]);
// 查看详情
const handleDetail = (row) => {
  router.push({
    path: '/modelCompareTools/strengthCompareStandardDetail',
    query: { model: queryParams.aircraftModel, track: row.track, groupType: row.groupType, name: row.name, id: row.id }
  });
};
// 下载文件
const downloadFile = (res, fileName) => {
  const blob = new Blob([res]);
  const objUrl = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.setAttribute('href', objUrl);
  link.setAttribute('download', fileName);
  link.style.display = 'none';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};
// 下载文件
const handleDownload = (row) => {
  const obj = {
    aircraftModel: queryParams.aircraftModel,
    ids: [row.id]
  };
  downloadData(obj).then((res) => {
    const contentDisposition = res.headers['content-disposition'];
    if (contentDisposition) {
      // 使用正则表达式提取filename（注意：这里的正则需要根据实际Content-Disposition的格式进行调整）
      const filename = contentDisposition.match(/filename="?([^"]+)"?/)[1];
      const fileName = decodeURIComponent(filename);
      downloadFile(res.data, fileName);
    }
  });
};
const buttonLoading = ref(false);
const standardDialog = reactive({
  visible: false,
  title: '上传原始装机清单'
});
const dialogForm = reactive({
  aircraftModel: '',
  file: null,
  describe: '',
  track: ''
});

const beforeUpload = (data) => {
  return false;
};
const uploadRef = ref<UploadInstance>();
const handleExceed: UploadProps['onExceed'] = (files) => {
  uploadRef.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  uploadRef.value!.handleStart(file);
};
const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
  dialogForm.file = null;
  dialogFormRef.value.validateField(['file']);
};
const changeFile = (data) => {
  if (data.status === 'ready') {
    dialogForm.file = data.raw;
    dialogFormRef.value.validateField(['file']);
  }
};
let diaLoading = ref(false);
const handleSure = async () => {
  await dialogFormRef.value.validate((valid, fields) => {
    if (valid) {
      let formData = new FormData();
      formData.set('file', dialogForm.file);
      formData.set('describe', dialogForm.describe);
      formData.set('track', dialogForm.track);
      diaLoading.value = true;
      uploadModelStatus(dialogForm.aircraftModel, formData)
        .then((res) => {
          diaLoading.value = false;
          if (res.code === 200) {
            proxy?.$modal.msgSuccess('上传数模状态清单成功');
            statusDialog.visible = false;
            handleQuery();
          }
        })
        .catch(() => {
          diaLoading.value = false;
        });
    } else {
      proxy?.$modal.msgError('请填写完整数据！');
    }
  });
};
const cancelCreate = () => {
  statusDialog.visible = false;
};

const openCreateStatusList = () => {
  statusDialog.visible = true;
};
const compareStrengthList = () => {
  if (!multipleSelection.value.length) {
    proxy?.$modal.msgWarning('请至少选择一条数据！');
  } else {
    // dialogVisible.value = true;
    // selectListDialogRef.value.openDialog();
    const obj = {
      aircraftModel: queryParams.aircraftModel,
      bomDetailType: 'MSTS_QBOM_CHANGE',
      compareTrack: '',
      bomIds: multipleSelection.value.map((item) => item.id)
    };
    generateList(obj).then((res) => {
      if (res.code === 200) {
        // dialogVisible.value = false;
        // selectListDialogRef.value.closeDialog();
        proxy?.$modal.msgSuccess('对比强度清单完成！');
      }
    });
  }
};
const handleDialogClose = () => {
  dialogVisible.value = false;
};
const handleDialogSure = (data) => {
  // console.log(data.track);
  const obj = {
    aircraftModel: queryParams.aircraftModel,
    bomDetailType: 'MSTS_QBOM_CHANGE',
    compareTrack: data.track,
    bomIds: multipleSelection.value.map((item) => item.id)
  };
  generateList(obj).then((res) => {
    if (res.code === 200) {
      // dialogVisible.value = false;
      selectListDialogRef.value.closeDialog();
      proxy?.$modal.msgSuccess('对比强度清单完成！');
    }
  });
};
const modelList = async () => {
  const res = await getStructureTree();
  airModelList.value = res.data.map((item) => {
    return {
      value: item.mark,
      label: item.name
    };
  });
};
onMounted(() => {
  modelList();
});
</script>

<style lang="scss" scoped></style>
